<?php

namespace app\agent\controller;

use app\common\controller\Agent;
use app\common\model\Notice;
use app\common\model\User;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Db;
use think\Exception;

/**
 * 提现申请
 *
 * @icon fa fa-circle-o
 */
class Withdraw extends Agent
{
    protected $relationSearch = true;

    protected $searchFields = 'id,user.username,order_sn';
    
    /**
     * Withdraw模型对象
     * @var \app\common\model\Withdraw
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Withdraw;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isDepositList", $this->model->getIsDepositList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/agent/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            $agent=$this->auth->getUserInfo();
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->withJoin('user')
                    ->where($where)
                    ->where('user_id','=',$agent['id'])
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->withJoin('user')
                    ->where($where)
                    ->where('user_id','=',$agent['id'])
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible([
                    'id','user_id','money','type','account','name','memo','order_sn','status','tranfer_time','create_time','update_time','is_deposit',
                    'user'=>['username']
                ]);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row)
            $this->error('未找到体现信息');

        if ($this->request->isPost()) {
            $this->error('不可更新信息');
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $withdraw_min = Config::get('site.withdraw_min')?:0;
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();

                try {
                    $agent=$this->auth->getUserInfo();
                    $user=User::get($agent['id']);
                    if($params['money']>$user['money']){
                        throw new Exception('提现金额大于账户余额');
                    }
                    if($params['money']<$withdraw_min){
                        throw new Exception("未到达最小提现金额{$withdraw_min}");
                    }
                    if(!$params['type']){
                        throw new Exception('请选择提现渠道');
                    }
                    if(!$params['account']){
                        throw new Exception('请输入提现账号');
                    }
                    if(!$params['name']){
                        throw new Exception('请输入账号名');
                    }

                    $payment_type='';
                    if ($params['type'] == 'alipay') {
                        $payment_type = '到支付宝';
                    }
                    if ($params['type'] == 'wechat') {
                        $payment_type = '到微信';
                    }

                    $params['user_id']=$user['id'];
                    $params['order_sn']=makePaySn($user['id']);
                    $params['memo'] = "城市代理人后台-提现{$params['money']}元到{$payment_type}";

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
                    $result = $this->model->save($params);

                    User::money(-1*$params['money'],$user['id'],$params['memo']);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("withdraw_min", $withdraw_min);

        return $this->view->fetch();
    }
}
